<?php
/**
 * Created by PhpStorm.
 * User: songshuai
 * Date: 2019/5/30
 * Time: 15:51
 */

namespace App\admin\Service;


use App\Jobs\Fun;
use App\Models\User\UserModel;
use Couchbase\Exception;

class OA
{
    /** 正常 */
    const ok = 0;
    /** 权限错误 */
    const Permission_error = -1;
    /** 参数错误 */
    const Parameter_error = -2;
    /** 没有数据 */
    const nullData = -3;
    /** 需要登录 */
    const Login = -1001;
    const Guest=-1001;

    public function __construct()
    {
        if (self::$user === null) {
            self::$user = new UserModel();
        }
    }

    static $_oa = null;

    public static function load()
    {
        if (self::$_oa === null) {
            self::$_oa = new self();
        }
    }
    /*
    const ApiPath = '/home/api/call/?c=';
    const staticPath = '/home/start/';
    */
    /**
     * 返回用户状态对象
     * @var   UserModel ;
     */
    public static $user = null;
    public static $_callFun = null;

    public static function Json($code, $data = 'ok', $msg = null)
    {
        if ($code !== 0 && $code !== 200) {
            $msg = $msg ? $msg : $data;
        }

        /* if(!Fun::isAjax()){
             $msg=$msg?$msg:$data;
              Fun::showmsg($msg);
          }*/
        self::$_apiMsg .= $msg;
        self::echoJson([
            'code' => $code,
            'data' => $data,
            'msg' => $msg
        ], $code == 0 || $code === OA::Login || $code === 200);
        exit;
    }

    static $_apiMsg = '';

    public static function echoJson($json, $apiSuccess = true)
    {
        if (self::$_callFun) {
            $run = \Closure::bind(self::$_callFun, null);
            $run($apiSuccess, self::$_apiMsg);
        }

        if (empty($json)) {
            echo '[]';
            exit;
        }
        //print_r($json);exit;
        $json['sql'] = self::$_SQL;
        $obj = json_encode($json);///JSON_UNESCAPED_UNICODE
        if ($obj === false) {
            /*   LogModel::Add(0,'json转换错误:'.json_last_error_msg(),LogModel::state_fail
                   , 0);*/
            throw new Exception(json_last_error_msg());
        }

        echo $obj;
        exit;
    }

    public static function RunCall($_callFun)
    {
        self::$_callFun = $_callFun;
    }

    public static $_SQL = null;
    /***/

}
